<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 卡片容器 -->
    <base-table-card>
      <template #header-left>
        <el-tabs v-model="searchParams.brandStatus" @tab-change="loadGetTableData">
          <el-tab-pane label="正常" :name="1" />
          <el-tab-pane label="已停用" :name="0" />
        </el-tabs>
      </template>
      <template #header-right>
        <el-button type="primary" @click="handleOpenAddDialog">新增品牌</el-button>
      </template>
      <avue-crud
        ref="avueCrudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        :before-open="handleBeforeOpen"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <template #categories-form>
          <el-cascader
            v-model="formData.categories"
            :options="categoryOptions"
            :props="categoryProps"
            clearable
            filterable
            :style="{ width: '100%' }"
          />
        </template>

        <template #img="{ row }">
          <el-image style="width: 100px; height: 100px" :src="row.img" :fit="'contain'" @click="showPreview(row.img)" />
        </template>

        <template #img-form>
          <el-upload
            class="avatar-uploader"
            action="#"
            :limit="1"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="uploadBrandImage"
            accept=".png,.jpeg,.jpg"
          >
            <el-image v-if="formData.img" :src="formData.img" fit="contain" style="width: 100px; height: 100px" />
            <base-icon v-else name="iconfont-general gen-zhaoxiangji" :size="44" color="var(--bd7)" />
            <!-- <el-icon v-else class="avatar-uploader-icon">

            </el-icon> -->
          </el-upload>
        </template>

        <template #menu="{ row }">
          <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
          <el-button type="primary" text @click="handleToggleDisplay(row)" v-if="row.brandStatus === 1">停用</el-button>
          <el-button type="primary" text @click="handleToggleDisplay(row)" v-else>启用</el-button>
          <el-button v-if="row.brandStatus === 0" type="danger" text @click="loadDel(row)"> 删除 </el-button>
        </template>
      </avue-crud>
    </base-table-card>
    <!-- 文件预览组件 -->
    <base-preview v-model:visible="visible" :index="0" :file-list="stringFileList" />
  </base-container>
  <!-- 使用 BaseDialog -->
  <!-- <BaseDialog
    v-model="showDialog"
    title="新增品牌"
    width="404px"
    :show-footer="true"
    cancel-text="取消"
    confirm-text="保存"
    @cancel="handleCancel"
    @confirm="handleConfirm"
  >
    <div class="sticky-header">请选择要进入的品牌:</div>
  </BaseDialog> -->
</template>

<script setup>
  import Option from "@/crudOption/goods/brand";
  import { ElMessageBox } from "element-plus";

  onMounted(() => {
    // 获取表格数据
    loadGetTableData();
  });

  // // 自定义上传：调用通用上传接口，并将返回 url 写入表单
  // async function uploadBrandImage({ file, onError, onSuccess }) {
  //   debugger
  //   try {
  //     const form = new FormData();
  //     form.append("file", file);
  //     // 可按需传 fileType 等参数
  //     // 添加文件类型等参数
  //     const res = await Api.files.commonUpload(form, { fileType:'01', isSecretFile:0 });
  //     // 兼容不同返回结构，取第一个可用的 url 字段
  //     const payload = res?.data ?? {};
  //     const url = payload.url || payload.fileUrl || payload.data?.url || payload.data?.fileUrl;
  //     if (!url) throw new Error("No url in upload response");
  //     formData.value = { ...formData.value, img: url };
  //     onSuccess && onSuccess(res);
  //   } catch (e) {
  //     ElMessage.error("图片上传失败");
  //     onError && onError(e);
  //   }
  // }
  /* ================== 启用或停用（确认 + loading） ================== */
  async function handleToggleDisplay(row) {
    const nextVal = row.brandStatus === 1 ? 0 : 1;
    const msg = nextVal === 0 ? "确定要停用该品牌吗？" : "确定要启用该品牌吗？";

    try {
      await ElMessageBox.confirm(msg, "提示", { type: "warning" });
      row._statusLoading = true;
      await Api.goods.brandChangeStatus({ id: row.id, brandStatus: nextVal });
      // row.categoryStatus = nextVal; // 手动切换
      loadGetTableData();
      $msg.success(nextVal ? "已启用" : "已停用");
    } catch (e) {
      console.log("🚀 ~ handleToggleDisplay ~ e:", e);
      // 取消/失败，不变
    } finally {
      row._statusLoading = false;
    }
  }
  // 文件上传
  const uploadBrandImage = file => {
    const form = new FormData();
    form.append("file", file.raw);
    Api.common.fileUpload(form).then(res => {
      formData.value.img = res.data;
      // nextTick(() => {
      //   uploadRef.value.clearFiles();
      // });
    });
  };
  const visible = ref(false);
  const stringFileList = ref([]);
  // 图片预览
  const showPreview = val => {
    stringFileList.value = [val];
    visible.value = true;
  };
  const categoryProps = {
    multiple: true,
    // checkStrictly: true,
    emitPath: true,
    value: "id",
    label: "name",
    children: "children",
  };
  const categoryOptions = ref([]);

  // 分类树由接口返回，构造函数已移除

  async function loadCategoryOptions() {
    try {
      const res = await Api.goods.categoryList({ pageNumber: 1, pageSize: 9999, categoryStatus: 1 });
      if (res?.data?.records) {
        categoryOptions.value = res.data.records.filter(item => {
          return item.children?.length > 0;
        });
      } else {
        categoryOptions.value = [];
      }
    } catch {
      categoryOptions.value = [];
    }
  }

  // avue-crud 组件实例
  const avueCrudRef = ref({});

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    del: loadDel,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.goods.brandPage,
    add: Api.goods.brandAdd,
    edit: Api.goods.brandUpdate,
    del: Api.goods.brandDelete,
    dataRes: "data.records",
    search: { brandStatus: 1 },
    getParamsFormat: params => {
      // 新增时间
      console.log("🚀 ~ params:", params);
      if (params.createTime && params.createTime.length === 2) {
        params.createBeginTime = `${params.createTime[0]} 00:00:00`;
        params.createEndTime = `${params.createTime[1]} 23:59:59`;
        delete params.createTime;
      }
      // 编辑时间
      if (params.updateTime && params.updateTime.length === 2) {
        params.updateBeginTime = `${params.updateTime[0]} 00:00:00`;
        params.updateEndTime = `${params.updateTime[1]} 23:59:59`;
        delete params.updateTime;
      }
      // 返回查询参数
      return params;
    },
    addParamsFormat: row => ({
      ...row,
      categories: (Array.isArray(row.categories) ? row.categories : [])
        .map(p => (Array.isArray(p) && p.length >= 2 ? { levelOneId: Number(p[0]), levelTwoId: Number(p[1]) } : null))
        .filter(Boolean),
    }),
    editParamsFormat: row => ({
      ...row,
      categories: (Array.isArray(row.categories) ? row.categories : [])
        .map(p => (Array.isArray(p) && p.length >= 2 ? { levelOneId: Number(p[0]), levelTwoId: Number(p[1]) } : null))
        .filter(Boolean),
    }),
  });

  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option(formData);

  // 弹窗打开前
  const handleBeforeOpen = done => {
    // 打开前刷新一次类目选项
    loadCategoryOptions();
    nextTick(done);
  };

  // 已移除无关的菜单树逻辑

  // 打开新增弹窗
  const handleOpenAddDialog = () => {
    formData.value = { ...formData.value };
    avueCrudRef.value.rowAdd();
  };

  // 将后端返回的 categories 回显为级联需要的路径数组
  function mapCategoriesToPaths(categories) {
    if (!Array.isArray(categories)) return [];
    return categories
      .map(i => {
        const l1 = i?.levelOneId;
        const l2 = i?.levelTwoId;
        if (l1 == null || l2 == null) return null;
        return [Number(l1), Number(l2)];
      })
      .filter(Boolean);
  }

  // 编辑时回显数据
  function handleEdit(row) {
    const paths = mapCategoriesToPaths(row?.categories);
    row.categories = paths;
    avueCrudRef.value?.rowEdit({
      ...row,
    });
  }
</script>

<style lang="scss" scoped>
  .avatar-uploader {
    width: 100px;
    height: 100px;
    border: 1px dashed #ccc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    .upload-btn {
      width: 100px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      .class-img {
        width: 100%;
        height: 100%;
      }
    }
  }
</style>
